package com.huan.springcloud.mongo;

import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LetterServiceImpl implements ILetterService{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Letter addLetter(Letter letter) {
        return mongoTemplate.insert(letter);
    }

    @Override
    public List<Letter> selectAllLetters() {
        return mongoTemplate.findAll(Letter.class,"letters");
    }

    @Override
    public List<Letter> selectLettersByPage(int curPage, int pageSize) {
        Query query=new Query();//Query是条件构造器
        //从第1页开始
        //分页查询，query.skip((curPage-1)*size).limit(size)表示跳过（当前页-1）*每页的大小条数据，输出size条数据
        return mongoTemplate.find(query.skip((curPage-1)*pageSize).limit(pageSize),Letter.class);
    }

    @Override
    public DeleteResult deleteLetterById(String id) {
        Query query=new Query(Criteria.where("_id").is(id));
        return mongoTemplate.remove(query,Letter.class);
    }

    @Override
    public long letterCount() {
        Query query=new Query();
        return mongoTemplate.count(query,Letter.class);
    }
}
